package com.acme.bankapp.domain.bank;
import com.acme.bankapp.domain.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

public class Bank {
	
	private int numOfClients;
	private int maxNumClients;
	private int maxNumListener = 2;
	private Client[] clients;
	private ClientRegistrationListener [] listeners;
	
	public Bank(int maxNumClients, Client[] clients) {
		numOfClients = 0;
		this.maxNumClients = maxNumClients;
		this.clients = clients;
		listeners = new ClientRegistrationListener[maxNumListener];	
		
		if (maxNumListener < 2) {
			System.out.println("the wrong number of listeners");
			return;
		}
		
		listeners[0] = new ClientRegistrationListener() {		   
			   
			public void onClientAdded(Client c) {
			   System.out.println(c);
			}
		 };	
			   
		 listeners[1] = new ClientRegistrationListener() {
					   
			  public void onClientAdded(Client c) {
					System.out.println("Notification email for client " + c.getClientSalutation() +
				" to be sent");
			  }		
		};			
	}
	
	public Bank(Client client) {
		this(10, new Client []{client});
	}
	
	public Bank() {
		this(10, new Client [2]);
	}
	
	public int getMaxNumClients() {
		return maxNumClients;
	}
	
	public int getNumClients() {
		return numOfClients;
	}
	
	public Client getClient (int num) {
		if (num > this.numOfClients) {
			return null;
		}
		return clients[num]; 
	}	
	
	public int addClient (Client client) throws ClientExistsException {
		
		for(int i = 0; i < numOfClients; i++) {
			if (client.getClientName().equals(clients[i])) {
				throw new ClientExistsException("this client already exists");
			}
		}
		
		if (numOfClients >= maxNumClients) {
			System.out.println("too many clients");
			return 1;			
		} 
		
		for (int i = 0; i < maxNumListener; i++) {
			listeners[i].onClientAdded(client);
		}
		
		clients[numOfClients] = client;
		numOfClients++;
		return 0;
	}

}
